import Vue from 'vue'
import Vuex from 'vuex'
import router from '../router'

Vue.use(Vuex)

import {login,userInfo} from '../api/api'
import {Toast} from "vant";
export default new Vuex.Store({
  state: {
    //登录状态
    isLogin:false,
    //用户信息
    userInfo:{}
  },
  mutations: {
    //修改登录状态
    changeLogin(state,payload){
      state.isLogin=payload
    },
    //修改个人信息
    changeInfo(state,payload){
      state.userInfo=payload
    }
  },
  actions: {
    Login(context,value){
      login(value.username,value.password,value.remberMe).then(res=>{
        // console.log(value.username,value.password,value.remberMe)
        // console.log(res)
        if(res.code==0){
          Toast.success('登陆成功！');
          //改变登录状态
          context.commit('changeLogin',true)
          //获取用户信息
          userInfo().then(res=>context.commit('changeInfo',res.data))
         // 跳转主页
          setTimeout(()=>router.push('/index'),1000)
        }else{
          Toast.fail('用户不存在/密码错误！');
        }
      });
    },

    //获取当前登录状态
    getUserInfo(context){
      userInfo().then(res=>{
        if(res.code == '0'){
          context.commit('changeInfo',res.data)
          context.commit('changeLogin',true)
        }else{
          context.commit('changeInfo',{})
          context.commit('changeLogin',false)
        }
      })
    }
  },
  modules: {
  }
})
